import 'dart:convert';

import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:ali_plugin/ali_plugin.dart';
import 'package:ali_log/ali_log.dart';
// import 'package:ali_crash_report/ali_crash_report.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();

  Future.delayed(Duration(seconds: 3), () {
    FlutterError.onError = (FlutterErrorDetails details) {
      reportErrorAndLog(details);
    };
    ///Flutter中与一个Zone的概念，Dart中可通过Zone表示指定代码执行的环境，不同的Zone代码上下文是不同的互不影响。类似一个沙盒概念，不同沙箱的之间是隔离的，沙箱可以捕获、拦截或修改一些代码行为，我们可以再这里面捕获所有没有被处理过的异常
    runZoned(() {
      runApp(MyApp());
    }, zoneSpecification: ZoneSpecification(
      ///zoneSpecification：Zone的一些配置，可以自定义一些代码行为，比如拦截日志输出行为等
//    print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
//    },
    ), onError: (dynamic error, StackTrace stack) {
      var details = makeDetails(error, stack);
      reportErrorAndLog(details);
    });
  });
}

///自定义上报flutter错误
reportErrorAndLog(FlutterErrorDetails details) {
  //TODO 具体实现可以通过 MethodChannel 传递给Platform
  print('customerReport-error:${details.exceptionAsString()}, stack:\n${details.stack.toString()}');
  AliLog.postDartError(details.exceptionAsString(), details.stack.toString());

}

makeDetails(dynamic error, StackTrace stack) {
  return FlutterErrorDetails(
    exception: error,
    stack: stack,
  );
}


class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  String _deviceId = 'Unknown';
  ///授权返回
  String authReturn;
  ///支付返回
  String payReturn;
  ///绑定返回
  String bindReturn;
  String unBindReturn;
  ///推送消息
  String messageMethod;
  String message;
  @override
  void initState() {
    super.initState();
    initDeviceId();
    initPlatformState();
    initAliPush();
    initBindListener();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      platformVersion = await AliPlugin.platformVersion;
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }
  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initDeviceId() async {
    String deviceId;
    // Platform messages may fail, so we use a try/catch PlatformException.
    try {
      deviceId = await AliPlugin.deviceId;
    } on PlatformException {
      deviceId = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    setState(() {
      _deviceId = deviceId;
    });
  }

  void initAliPush() {
    AliPlugin.messageListener = new AliPushMessageListener(
        onNoticationCall: (value){
          print('_MyAppState.onNoticationCall-value:$value');
          messageMethod = 'onNoticationCall';
          _updateMessage(value);
        },
        onMessageCall: (value){
          print('_MyAppState.onMessageCall-value:$value');
          messageMethod = 'onMessageCall';
          _updateMessage(value);
        },
        onNotificationOpenedCall: (value){
          print('_MyAppState.onNotificationOpenedCall-value:$value');
          messageMethod = 'onNotificationOpenedCall';
          _updateMessage(value);
        }
    );
  }
  void initBindListener(){
    AliPlugin.bindListener = AliBindPushListener(
      onBindSuccessCall: (value){
        _updateBindReturn('绑定成功:$value');
      },
      onBindFailedCall: (value){
        _updateBindReturn('绑定失败:$value');
      },
      onUnBindSuccessCall: (value){
        unBindReturn = "解绑成功";
        bindReturn = null;
        setState(() {

        });
      }
    );
  }
  _updateBindReturn(String value){
    print('_MyAppState._updateBindReturn');
    setState(() {
      unBindReturn = null;
      bindReturn = value;
    });
  }
  _updateMessage(String value){
    setState(() {
      message = value;
    });
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
            child: Column(
              children: <Widget>[
                Text('Running on: $_platformVersion\n'),
                Text('push DeviceId: $_deviceId\n'),
                RaisedButton(
                  onPressed: (){
                    AliPlugin.authCallBack = (value){
                      authReturn = jsonEncode(value);
                      print('_MyAppState.authCallBack -value:$authReturn}');
                      setState(() {

                      });
                    };
                    //authInfo 根据商户的授权请求信息生成。详见授权请求参数 https://opendocs.alipay.com/open/218/105327
                    String authInfo = "apiname=com.alipay.account.auth&app_id=xxxxx&app_name=mc&auth_type=AUTHACCOUNT&biz_type=openservice&method=alipay.open.auth.sdk.code.get&pid=xxxxx&product_id=APP_FAST_LOGIN&scope=kuaijie&sign_type=RSA2&target_id=20141225xxxx&sign=fMcp4GtiM6rxSIeFnJCVePJKV43eXrUP86CQgiLhDHH2u%2FdN75eEvmywc2ulkm7qKRetkU9fbVZtJIqFdMJcJ9Yp%2BJI%2FF%2FpESafFR6rB2fRjiQQLGXvxmDGVMjPSxHxVtIqpZy5FDoKUSjQ2%2FILDKpu3%2F%2BtAtm2jRw1rUoMhgt0%3D";
                    AliPlugin.toAuth(authInfo);
                  },
                  child: Text('支付宝授权'),
                ),
                Offstage(
                  offstage: authReturn == null,
                  child: Text(authReturn==null?'授权结果:':'授权结果:$authReturn'),
                ),
                RaisedButton(
                  onPressed: (){
                    AliPlugin.payCallBack = (value){
                      payReturn = jsonEncode(value);
                      print('_MyAppState.payCallBack -value:$authReturn}');
                      setState(() {

                      });
                    };
                    //orderStr 支付请求参数字符串，主要包含商户的订单信息。详见请求参数 https://opendocs.alipay.com/open/204/105465/
                    String orderStr = "app_id=2015052600090779&biz_content=%7B%22timeout_express%22%3A%2230m%22%2C%22seller_id%22%3A%22%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.02%22%2C%22subject%22%3A%221%22%2C%22body%22%3A%22%E6%88%91%E6%98%AF%E6%B5%8B%E8%AF%95%E6%95%B0%E6%8D%AE%22%2C%22out_trade_no%22%3A%22314VYGIAGG7ZOYY%22%7D&charset=utf-8&method=alipay.trade.app.pay&sign_type=RSA2&timestamp=2016-08-15%2012%3A12%3A15&version=1.0&sign=MsbylYkCzlfYLy9PeRwUUIg9nZPeN9SfXPNavUCroGKR5Kqvx0nEnd3eRmKxJuthNUx4ERCXe552EV9PfwexqW%2B1wbKOdYtDIb4%2B7PL3Pc94RZL0zKaWcaY3tSL89%2FuAVUsQuFqEJdhIukuKygrXucvejOUgTCfoUdwTi7z%2BZzQ%3D";
                    AliPlugin.payOrder(orderStr);
                  },
                  child: Text('支付宝支付'),
                ),
                Offstage(
                  offstage: payReturn == null,
                  child: Text(payReturn==null?'支付结果:':'支付结果:$payReturn'),
                ),
                RaisedButton(
                  onPressed: (){
                    AliPlugin.bindAccount('2372');
                  },
                  child: Text('登录绑定测试'),
                ),
                Offstage(
                  offstage: bindReturn == null,
                  child: Text(bindReturn==null?'':'绑定结果:$bindReturn'),
                ),
                RaisedButton(
                  onPressed: (){
                    AliPlugin.unBindAccount();
                  },
                  child: Text('解绑测试'),
                ),
                Offstage(
                  offstage: unBindReturn == null,
                  child: Text(unBindReturn??''),
                ),
                Offstage(
                  offstage: messageMethod == null,
                  child: Text(messageMethod??''),
                ),
                Offstage(
                  offstage: message == null,
                  child: Text(message??''),
                ),
                ElevatedButton(
                  onPressed: (){
                    toError();
                  },
                  child: Text('dart exception 测试'),
                ),
                ElevatedButton(
                  onPressed: (){
                    AliLog.postHttpLog("testUrl", "testParams", "testResponseJson");
                  },
                  child: Text('http请求失败测试'),
                ),
                // ElevatedButton(
                //   onPressed: (){
                //     AliCrashReport.testCrash();
                //   },
                //   child: Text('崩溃测试'),
                // ),
                // ElevatedButton(
                //   onPressed: (){
                //     AliCrashReport.updateNick('nick_test');
                //   },
                //   child: Text('添加昵称'),
                // ),
              ],
            )
        ),
      ),
    );
  }

  toError(){
    var s = Scaffold.of(context).widget.bottomSheet.toString();
  }
}
